﻿using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Meridian.Helpers;
using Meridian.ViewModel;
using VkApi;

namespace Meridian
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        private const string AppId = "2635307";

        public static Settings Settings;
        public static readonly string Root = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        public static Vkontakte Vkontakte;
        public static LastFmHelper LastFmHelper;
        public static MediaElement Player;

        public static MainViewModel ViewModel { get; private set; }

        public App()
        {
            Vkontakte = new Vkontakte(AppId);
            ViewModel = new MainViewModel();
            LastFmHelper = new LastFmHelper();
        }

        private void ApplicationStartup(object sender, StartupEventArgs e)
        {
            Settings = (Settings)XmlSerializable.Load(typeof(Settings), Root + "\\Meridian.config") ?? new Settings();
            if (!string.IsNullOrEmpty(Settings.AccessToken) && Settings.ExpirationDate != DateTime.MinValue && !string.IsNullOrEmpty(Settings.UserId))
            {
                var authResult = new VkAuthResult(Settings.AccessToken, Settings.ExpirationDate, Settings.UserId);
                if (authResult.AccessToken.HasExpired)
                    return;
                Vkontakte.AuthResult = authResult;
                Global.IsAuthorized = true;
            }

            System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(Settings.Language);
            switch (Settings.AccentColor)
            {
                case "Red":
                    Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("/Resources/AccentColors/Red.xaml", UriKind.Relative) });
                    break;
                case "Green":
                    Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("/Resources/AccentColors/Green.xaml", UriKind.Relative) });
                    break;
                case "Pink":
                    Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("/Resources/AccentColors/Pink.xaml", UriKind.Relative) });
                    break;
                case "Mango":
                    Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("/Resources/AccentColors/Mango.xaml", UriKind.Relative) });
                    break;

            }

            if (Settings.Clean)
            {
                foreach (var file in Directory.GetFiles(Root, "*.old", SearchOption.AllDirectories))
                {
                    try
                    {
                        File.Delete(file);
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                    }
                }

                Settings.Clean = false;
            }
        }

        private void ApplicationExit(object sender, ExitEventArgs e)
        {
            if (Global.IsAuthorized)
            {
                Settings.AccessToken = Vkontakte.AuthResult.AccessToken.Token;
                Settings.ExpirationDate = Vkontakte.AuthResult.AccessToken.Expires;
                Settings.UserId = Vkontakte.AuthResult.UserId;
            }
            Settings.Save(Root + "\\Meridian.config");
        }

        private void ApplicationDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            logger.Fatal("An error occured.\n" + e.Exception);
            MessageBox.Show("An error occured. See details in log");
        }
    }
}
